<?php

namespace app\model;

use think\Model;
use think\model\relation\HasOne;

class StationRebateRule extends Model
{
    public function saveData(): array
    {
        $param = request()->post();
        $param['pro_lst'] = json_encode($param['pro_lst'] ?? [], 320);
        $param['oil_type'] = json_encode($param['oil_type'] ?? [], 320);
        $start_time = strtotime($param['start_time'] . ' 00:00:00');
        $end_time = strtotime($param['end_time'] . ' 23:59:59');
        if ($start_time > $end_time) throw new \Exception('开始时间不能大于结束时间');
        $param['state'] = $start_time < time() ? 1 : 0;
        if ($end_time < time()) $param['state'] = 2;
        $this->exists(!empty($param['id']))->save($param);
        return $this->toArray();
    }

    public function pageData(): array
    {
        $param = request()->param();
        $this->where('start_time','<=',date("Y-m-d"))->save(['state'=>1]);
        $this->where('end_time','<=',date("Y-m-d"))->save(['state'=>2]);
        $data = $this->with(['merchant', 'rule'])->order('create_time', 'desc')->paginate(['list_rows' => 30, 'page' => $param['page'] ?? 1])->toArray();
        return pageData($data);
    }

    public function merchant(): HasOne
    {
        return $this->hasOne(Merchant::class, 'id', 'mid');
    }

    public function rule(): HasOne
    {
        return $this->hasOne(StationRebate::class, 'id', 'rule_id');
    }
}
